import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Form, Input, Button, message, Tag, Divider, Select, InputNumber } from 'antd';
import { PlusOutlined, DeleteOutlined, CopyOutlined } from '@ant-design/icons';
import { Parameter, ParameterValue, Project } from '../../types';

interface ParameterValueFormProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: string[]) => Promise<void>;
  parameter: Parameter | null;
  initialValues?: ParameterValue[];
  title: string;
  project?: Project | null;
}

const ParameterValueForm: React.FC<ParameterValueFormProps> = ({
  visible,
  onCancel,
  onSubmit,
  parameter,
  initialValues = [],
  title,
  project
}) => {
  const [form] = Form.useForm();
  const [values, setValues] = useState<string[]>(['']);
  const [showYearLabels, setShowYearLabels] = useState(false);

  // 获取参数的默认值（根据类型）
  const getDefaultValue = (paramType: string): string => {
    switch (paramType) {
      case 'integer':
      case 'float':
        return '0';
      case 'boolean':
        return 'false';
      case 'string':
      default:
        return '';
    }
  };

  // 当参数或初始值变化时，更新表单
  useEffect(() => {
    if (visible && parameter) {
      if (initialValues && initialValues.length > 0) {
        // 对于列表参数，按 list_index 排序
        const sortedValues = [...initialValues].sort((a, b) => (a.list_index || 0) - (b.list_index || 0));
        const initialValuesList = sortedValues.map(v => v.value);
        setValues(initialValuesList.length > 0 ? initialValuesList : ['']);
      } else {
        // 如果参数关联年份，根据项目时间长度初始化输入框数量
        if (parameter.is_year_related && project) {
          const timeHorizon = project.time_horizon;
          setValues(Array(timeHorizon).fill(''));
        } else if (parameter.list_length && parameter.list_length > 0) {
          // 如果参数有列表长度，根据列表长度和类型初始化带默认值的输入框
          const defaultValue = getDefaultValue(parameter.param_type);
          setValues(Array(parameter.list_length).fill(defaultValue));
        } else {
          setValues(['']);
        }
      }
      // 根据参数的年份关联状态设置开关
      setShowYearLabels(parameter.is_year_related || false);
    } else if (visible) {
      setValues(['']);
      setShowYearLabels(false);
    }
  }, [visible, parameter?.id, parameter?.is_year_related, parameter?.list_length, parameter?.param_type, project?.time_horizon, initialValues?.length]);

  const handleAddValue = useCallback(() => {
    setValues(prev => [...prev, '']);
  }, []);

  const handleRemoveValue = useCallback((index: number) => {
    setValues(prev => {
      if (prev.length > 1) {
        return prev.filter((_, i) => i !== index);
      }
      return prev;
    });
  }, []);

  const handleValueChange = useCallback((index: number, value: string) => {
    setValues(prev => {
      const newValues = [...prev];
      newValues[index] = value;
      return newValues;
    });
  }, []);

  // 一键填充功能：将所有后续值设置为第一个非空值
  const handleFillAllValues = useCallback(() => {
    const firstValue = values[0]?.trim();
    if (!firstValue) {
      message.warning('请先输入第一个值');
      return;
    }
    
    // 将所有值设置为第一个值
    const filledValues = values.map(() => firstValue);
    setValues(filledValues);
    message.success('已一键填充所有值');
  }, [values]);


  // 计算年份标签
  const getYearLabel = useCallback((index: number) => {
    if (!project || !showYearLabels) return '';
    
    const year = project.start_year + (index * project.year_step);
    return `${year}年`;
  }, [project, showYearLabels]);

  const validateValues = (values: string[]) => {
    if (!parameter) return true;

    for (let i = 0; i < values.length; i++) {
      const value = values[i].trim();
      
      // 对于关联年份的参数，空值也需要验证
      if (value === '' && !parameter.is_year_related) continue;

      switch (parameter.param_type) {
        case 'integer':
          if (value !== '' && (!Number.isInteger(Number(value)) || Number(value) !== parseInt(value))) {
            message.error(`第 ${i + 1} 个值必须是整数`);
            return false;
          }
          break;
        case 'float':
          if (value !== '' && isNaN(Number(value))) {
            message.error(`第 ${i + 1} 个值必须是数字`);
            return false;
          }
          break;
        case 'boolean':
          if (value !== '' && value !== 'true' && value !== 'false') {
            message.error(`第 ${i + 1} 个值必须是 true 或 false`);
            return false;
          }
          break;
        case 'string':
        default:
          // 字符串类型不需要特殊验证
          break;
      }
    }
    return true;
  };

  const handleSubmit = async () => {
    try {
      // 对于关联年份的参数或设置了固定长度的参数，提交所有值（包括默认值）
      // 对于非关联年份且没有固定长度的参数，只提交非空值
      const needsAllValues = parameter?.is_year_related || (parameter?.list_length && parameter.list_length > 0);
      
      if (!needsAllValues) {
        // 对于非关联年份且没有固定长度的参数，过滤掉空值
        const nonEmptyValues = values.filter(v => v.trim() !== '');
        if (nonEmptyValues.length === 0) {
          message.warning('请至少输入一个参数值');
          return;
        }
      }

      // 验证数据类型（只为非空值验证）
      const valuesToCheck = needsAllValues ? values : values.filter(v => v.trim() !== '');
      if (!validateValues(valuesToCheck)) {
        return;
      }

      const valuesToSubmit = needsAllValues ? values : values.filter(v => v.trim() !== '');
      
      await onSubmit(valuesToSubmit);
      form.resetFields();
      setValues(['']);
    } catch (error: any) {
      console.error('Parameter value form submit failed:', error);
      
      // 显示后端返回的具体错误信息
      if (error?.response?.data?.detail) {
        message.error(error.response.data.detail);
      } else if (error?.message) {
        message.error(error.message);
      } else {
        message.error('设置参数值失败');
      }
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setValues(['']);
    onCancel();
  };


  const formatValue = (value: string) => {
    if (!parameter) return value;
    
    switch (parameter.param_type) {
      case 'boolean':
        return value === 'true' ? '是 (true)' : value === 'false' ? '否 (false)' : value;
      case 'integer':
        return Number.isInteger(Number(value)) ? parseInt(value).toString() : value;
      case 'float':
        return !isNaN(Number(value)) ? parseFloat(value).toString() : value;
      case 'string':
      default:
        return value;
    }
  };

  const renderValueInput = (value: string, index: number) => {
    if (!parameter) return null;

    switch (parameter.param_type) {
      case 'integer':
        return (
          <InputNumber
            value={value !== '' ? parseInt(value) : undefined}
            onChange={(val) => handleValueChange(index, val !== null && val !== undefined ? val.toString() : '')}
            placeholder={`输入整数值 ${index + 1}`}
            style={{ flex: 1, marginRight: 8 }}
            precision={0}
            step={1}
          />
        );
      
      case 'float':
        return (
          <InputNumber
            value={value !== '' ? parseFloat(value) : undefined}
            onChange={(val) => handleValueChange(index, val !== null && val !== undefined ? val.toString() : '')}
            placeholder={`输入数值 ${index + 1}`}
            style={{ flex: 1, marginRight: 8 }}
            step={0.1}
          />
        );
      
      case 'boolean':
        return (
          <Select
            value={value}
            onChange={(val) => handleValueChange(index, val)}
            placeholder={`选择布尔值 ${index + 1}`}
            style={{ flex: 1, marginRight: 8 }}
            options={[
              { label: '是 (true)', value: 'true' },
              { label: '否 (false)', value: 'false' }
            ]}
          />
        );
      
      case 'string':
      default:
        return (
          <Input
            value={value}
            onChange={(e) => handleValueChange(index, e.target.value)}
            placeholder={`输入字符串值 ${index + 1}`}
            style={{ flex: 1, marginRight: 8 }}
          />
        );
    }
  };

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={handleCancel}
      onOk={handleSubmit}
      okText="确定"
      cancelText="取消"
      width={600}
      destroyOnHidden
    >
      {parameter && (
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>
            <strong>参数名称：</strong>
            <span style={{ 
              background: '#f0f0f0',
              color: '#666',
              padding: '3px 8px',
              borderRadius: '4px',
              fontSize: '12px',
              fontWeight: 500,
              border: '1px solid #d9d9d9',
              marginLeft: 8
            }}>
              {parameter.name}
            </span>
          </div>
          <div style={{ marginBottom: 8 }}>
            <strong>英文名称：</strong>
            <span style={{ 
              background: '#e6f7ff',
              color: '#1890ff',
              padding: '3px 8px',
              borderRadius: '4px',
              fontSize: '12px',
              fontWeight: 500,
              border: '1px solid #91d5ff',
              marginLeft: 8
            }}>
              {parameter.name_en}
            </span>
          </div>
          <div style={{ marginBottom: 8 }}>
            <strong>参数类型：</strong>
            <span style={{ 
              background: parameter.param_type === 'integer' ? '#e6f7ff' : 
                         parameter.param_type === 'float' ? '#f6ffed' :
                         parameter.param_type === 'boolean' ? '#fff7e6' : '#f9f0ff',
              color: parameter.param_type === 'integer' ? '#1890ff' : 
                     parameter.param_type === 'float' ? '#52c41a' :
                     parameter.param_type === 'boolean' ? '#fa8c16' : '#722ed1',
              padding: '3px 8px',
              borderRadius: '4px',
              fontSize: '12px',
              fontWeight: 500,
              border: parameter.param_type === 'integer' ? '1px solid #91d5ff' : 
                      parameter.param_type === 'float' ? '1px solid #b7eb8f' :
                      parameter.param_type === 'boolean' ? '1px solid #ffd591' : '1px solid #d3adf7',
              marginLeft: 8
            }}>
              {parameter.param_type === 'integer' ? '整数' : 
               parameter.param_type === 'float' ? '浮点数' :
               parameter.param_type === 'boolean' ? '布尔值' : '字符串'}
            </span>
          </div>
          {parameter.unit && (
            <div style={{ marginBottom: 8 }}>
              <strong>单位：</strong>
              <span style={{ 
                background: 'linear-gradient(135deg, #f6ffed 0%, #f0f9e8 100%)',
                color: '#52c41a',
                padding: '3px 8px',
                borderRadius: '4px',
                fontSize: '11px',
                fontWeight: 600,
                border: '1px solid #b7eb8f',
                boxShadow: '0 1px 2px rgba(82, 196, 26, 0.1)',
                textTransform: 'uppercase',
                letterSpacing: '0.5px',
                marginLeft: 8
              }}>
                {parameter.unit}
              </span>
            </div>
          )}
          <div style={{ marginBottom: 8 }}>
            <strong>是否列表：</strong>
            <span style={{ 
              background: parameter.is_list ? '#f6ffed' : '#f0f0f0',
              color: parameter.is_list ? '#52c41a' : '#666',
              padding: '3px 8px',
              borderRadius: '4px',
              fontSize: '12px',
              fontWeight: 500,
              border: parameter.is_list ? '1px solid #b7eb8f' : '1px solid #d9d9d9',
              marginLeft: 8
            }}>
              {parameter.is_list ? '是' : '否'}
            </span>
          </div>
          {parameter.is_list && (
            <>
              <div style={{ marginBottom: 8 }}>
                <strong>关联年份：</strong>
                <span style={{ 
                  background: parameter.is_year_related ? '#e6f7ff' : '#f0f0f0',
                  color: parameter.is_year_related ? '#1890ff' : '#666',
                  padding: '3px 8px',
                  borderRadius: '4px',
                  fontSize: '12px',
                  fontWeight: 500,
                  border: parameter.is_year_related ? '1px solid #91d5ff' : '1px solid #d9d9d9',
                  marginLeft: 8
                }}>
                  {parameter.is_year_related ? '是' : '否'}
                </span>
              </div>
              {!parameter.is_year_related && parameter.list_length && (
                <div style={{ marginBottom: 8 }}>
                  <strong>列表长度：</strong>
                  <span style={{ 
                    background: '#fff7e6',
                    color: '#fa8c16',
                    padding: '3px 8px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    fontWeight: 500,
                    border: '1px solid #ffd591',
                    marginLeft: 8
                  }}>
                    {parameter.list_length}
                  </span>
                </div>
              )}
            </>
          )}
          {initialValues && initialValues.length > 0 && (
            <div style={{ marginBottom: 8 }}>
              <strong>参数值数量：</strong>
              <span style={{ 
                background: '#f0f0f0',
                color: '#666',
                padding: '3px 8px',
                borderRadius: '4px',
                fontSize: '12px',
                fontWeight: 500,
                border: '1px solid #d9d9d9',
                marginLeft: 8
              }}>
                {initialValues.length} 个值
              </span>
            </div>
          )}
          <Divider />
        </div>
      )}

      <Form
        form={form}
        layout="vertical"
        requiredMark={false}
      >
        <Form.Item label="参数值">
          <div>
            {values.map((value, index) => (
              <div key={index} style={{ marginBottom: 8, display: 'flex', alignItems: 'center' }}>
                {showYearLabels && project ? (
                  <div style={{ 
                    minWidth: '60px', 
                    marginRight: '8px', 
                    fontSize: '14px', 
                    fontWeight: 500,
                    color: '#1890ff',
                    textAlign: 'left'
                  }}>
                    {getYearLabel(index)}
                  </div>
                ) : (
                  <div style={{ 
                    minWidth: '40px', 
                    marginRight: '8px', 
                    fontSize: '14px', 
                    fontWeight: 500,
                    color: '#666',
                    textAlign: 'center',
                    background: '#f5f5f5',
                    borderRadius: '4px',
                    padding: '2px 6px',
                    border: '1px solid #d9d9d9'
                  }}>
                    {index + 1}
                  </div>
                )}
                <div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
                  {renderValueInput(value, index)}
                  {parameter?.unit && (
                    <span style={{ 
                      marginLeft: 8, 
                      background: 'linear-gradient(135deg, #f6ffed 0%, #f0f9e8 100%)',
                      color: '#52c41a',
                      padding: '3px 8px',
                      borderRadius: '4px',
                      fontSize: '11px',
                      fontWeight: 600,
                      border: '1px solid #b7eb8f',
                      boxShadow: '0 1px 2px rgba(82, 196, 26, 0.1)',
                      textTransform: 'uppercase',
                      letterSpacing: '0.5px',
                      minWidth: '40px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center'
                    }}>
                      {parameter.unit}
                    </span>
                  )}
                  {!parameter?.is_year_related && parameter?.is_list && !parameter?.list_length && values.length > 1 ? (
                    <Button
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => handleRemoveValue(index)}
                      style={{ marginLeft: 8 }}
                    />
                  ) : null}
                </div>
              </div>
            ))}
          </div>
          
          {parameter?.is_list && parameter.is_year_related && (
            <div style={{ marginTop: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
                <span style={{ fontSize: '14px', fontWeight: 500 }}>关联年份</span>
                <span style={{ fontSize: '12px', color: '#52c41a', fontWeight: 500 }}>
                  (已关联年份 - {project?.time_horizon}年)
                </span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
                <Button
                  type="primary"
                  icon={<CopyOutlined />}
                  onClick={handleFillAllValues}
                  style={{ flex: 1 }}
                >
                  一键填充所有年份
                </Button>
              </div>
              <div style={{ marginTop: 4, fontSize: '12px', color: '#8c8c8c', textAlign: 'center' }}>
                提示：输入第一个年份的值后，点击可快速填充所有年份
              </div>
            </div>
          )}
          
          {parameter?.is_list && !parameter.is_year_related && (
            <div style={{ marginTop: 16 }}>
              {/* 一键填充按钮 - 仅在列表参数且长度固定时显示 */}
              {parameter.list_length && parameter.list_length > 1 && (
                <>
                  <Button
                    type="primary"
                    icon={<CopyOutlined />}
                    onClick={handleFillAllValues}
                    style={{ width: '100%', marginBottom: 8 }}
                  >
                    一键填充所有值
                  </Button>
                  <div style={{ marginBottom: 8, fontSize: '12px', color: '#8c8c8c', textAlign: 'center' }}>
                    提示：输入第一个值后，点击可快速填充所有值
                  </div>
                </>
              )}
              {/* 添加按钮 - 仅在没有设置固定长度时显示 */}
              {!parameter.list_length && (
                <Button
                  type="dashed"
                  icon={<PlusOutlined />}
                  onClick={handleAddValue}
                  style={{ width: '100%' }}
                >
                  添加参数值
                </Button>
              )}
            </div>
          )}
        </Form.Item>

        {values.some(v => v.trim() !== '') && (
          <Form.Item label="预览">
            <div style={{ padding: 12, background: '#f5f5f5', borderRadius: 6 }}>
              {values
                .filter(v => v.trim() !== '')
                .map((value, index) => (
                  <Tag key={index} style={{ margin: '2px' }}>
                    {showYearLabels && project ? `${getYearLabel(index)}: ${formatValue(value)}` : formatValue(value)}
                  </Tag>
                ))}
            </div>
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default ParameterValueForm;
